﻿
/*jslint unparam: true */
/*global window, $ */
function setupUpload(id, folder) {
    'use strict';
    // Change this to the location of your server-side upload handler:
    var url = '/Services/Handler.ashx?dir=' + folder,
        uploadButton = $('<button/>')
            .addClass('btn btn-primary')
            .prop('disabled', true)
            .text('Processing...')
            .on('click', function () {
                var $this = $(this),
                    data = $this.data();
                $this
                    .off('click')
                    .text('Abort')
                    .on('click', function () {
                        $this.remove();
                        data.abort();
                    });
                data.submit().always(function () {
                    $this.remove();
                });
            });
    $('#fileupload').fileupload({
        url: url,
        dataType: 'json',
        autoUpload: true,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        maxFileSize: 50000000, // 5 MB
        // Enable image resizing, except for Android and Opera,
        // which actually support image resizing, but fail to
        // send Blob objects via XHR requests:
        disableImageResize: /Android(?!.*Chrome)|Opera/
            .test(window.navigator.userAgent),
        previewMaxWidth: 100,
        previewMaxHeight: 100,
        previewCrop: true
    }).on('fileuploadadd', function (e, data) {
        data.context = $('<div/>').appendTo('#files');
        $.each(data.files, function (index, file) {
            var node = $('<p/>')
                            .append($('<span/>').text(file.name));
            if (!index) {
                node.append('<br>');
                //                    .append(uploadButton.clone(true).data(data));
            }
            node.appendTo(data.context);
        });

    }).on('fileuploadprocessalways', function (e, data) {
        var index = data.index,
            file = data.files[index],
            node = $(data.context.children()[index]);
        if (file.preview) {
            node.prepend('<br>')
                .prepend(file.preview);
        }
        if (file.error) {
            node.append('<br>')
                .append($('<span class="text-danger"/>').text(file.error));
        }
        if (index + 1 === data.files.length) {
            data.context.find('button')
                        .text('Upload')
                        .prop('disabled', !!data.files.error);
        }
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('#progress .progress-bar').css(
            'width',
            progress + '%'
        );
    }).on('fileuploaddone', function (e, data) {
        $.each(data.result.files, function (index, file) {
            if (file.url) {
                var link = $('<a>')
                    .attr('target', '_blank')
                    .prop('href', file.url);
                $(data.context.children()[index])
                    .wrap(link);
            } else if (file.error) {
                var error = $('<span class="text-danger"/>').text(file.error);
                $(data.context.children()[index])
                    .append('<br>')
                    .append(error);
            }
        });
        getImageFiles(id, folder);
    }).on('fileuploadfail', function (e, data) {
        $.each(data.files, function (index) {
            var error = $('<span class="text-danger"/>').text('File upload failed.');
            $(data.context.children()[index])
                .append('<br>')
                .append(error);
        });
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');

    getImageFiles(id, folder);
}

$(document).ready(function () {
    // setup popup dialog
    $("#dialog-upload").dialog({
        autoOpen: false,
        width: 850,
        height: 600,
        modal: true,
        buttons: {
            "Chọn": function () {
                var $first = $('#file-explorer input[type=checkbox]:checked').first();
                if ($first !== 'undefined') {
                    var file = $first.closest('div').next().prop('title');
                    if (typeof acceptDialog === 'function')
                        acceptDialog(file);
                }
                $("#dialog-upload").dialog("close");
            },
            "Đóng": function () {
                $('#files').html('');
                $(this).dialog("close");
            }
        },
        close: function () {

        }
    });
});

var folders = 'tmp';
function getImageFiles(id, folder) {
    if (folder !== 'undefined')
        folders = '/images/' + folder + '/thumb/';
    $.ajax({
        type: "POST",
        url: "/Services/Handler.asmx/GetFileInfos",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify({ folder: folder }),
        async: false,
        success: function (data) {
            var list = data.d;
            $(id).html('');
            if (list.length > 0) {
                $(list).each(function (index, value) {
                    var filename = value;
                    if (value.length > 10) {
                        var afilename = value.split('.');
                        filename = afilename[0].substring(0, 10) + '..(.' + afilename[1] + ')';
                    }
                    $(id).append('<div class="image"><div class="img"><img src="' + folders + value + '" title="' + value + '" /></div><div class="roundedOne"><input type="checkbox" value="None" id="up' + index + '" name="check" /><label for="up' + index + '"></label></div><label title="' + value + '">' + filename + '</label><div>');
                });
            } else {
                $(id).append('<label class="no-image">Không có tập tin.</label>');
            }
        },
        error: function (xmlHttpRequest) {
            showMessage(xmlHttpRequest, 'failed');
        }
    });
}